package com.littleu.yojoincn.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.littleu.yojoincn.BO.TtLoginBO;
import com.littleu.yojoincn.BO.TtLoginResponseDataBO;
import com.littleu.yojoincn.common.enumeration.ScopeLevel;
import com.littleu.yojoincn.common.exception.http.ParameterException;
import com.littleu.yojoincn.common.exception.http.TtException;
import com.littleu.yojoincn.common.util.JwtToken;
import com.littleu.yojoincn.dto.tt.LoginDTO;
import com.littleu.yojoincn.model.CustomerDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Optional;

@Service
public class TtAuthService {
    @Value("${tt.appid}")
    private String appid;
    @Value("${tt.secret}")
    private String secret;
    @Value("${tt.code2session}")
    private String code2sessionUrl;

    @Autowired
    private CustomerService customerService;

    public String code2Session(String code) {
        LoginDTO dto = new LoginDTO();
        dto.setCode(code);
        dto.setAppid(appid);
        dto.setSecret(secret);
        TtLoginBO result = this.postRequest(dto);
        return this.registerCustomer(result);
    }

    private TtLoginBO postRequest(LoginDTO dto){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        SerializeConfig serializeConfig = new SerializeConfig();
        serializeConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String dtoString = JSONObject.toJSONString(dto,serializeConfig);

        HttpEntity<String> entity = new HttpEntity<String>(dtoString,headers);
        String result = restTemplate.postForObject(code2sessionUrl, entity, String.class);
        TtLoginBO resultObject = JSON.parseObject(result, TtLoginBO.class);
        System.out.println(result);
        assert resultObject != null;
        String success = (String) resultObject.getErrTips();
        if(!success.equals("success")){
            throw new TtException((String) resultObject.getErrTips());
        }
        return resultObject;
    }

    private String registerCustomer(TtLoginBO session){
        TtLoginResponseDataBO data = session.getData();
        String openid = data.getOpenid();
        if(openid == null){
            throw new ParameterException(20004);
        }
        CustomerDO customerDO = this.customerService.getBaseMapper().selectOneByOpenid(openid);
        if(Optional.ofNullable(customerDO).isPresent()){
            return JwtToken.makeToken(customerDO.getId());
        }
        CustomerDO customer = new CustomerDO();
        customer.setOpenid(openid);
        customer.setScope(ScopeLevel.USER.value());
        this.customerService.save(customer);
        Long cid = customer.getId();
        return JwtToken.makeToken(cid);
    }
}
